package com.api.league.service.impl;

import com.api.core.service.AbstractService;
import com.api.league.dao.LeagueTeamMapper;
import com.api.league.model.LeagueTeam;
import com.api.league.service.LeagueTeamService;
import com.api.league.vo.LeagueTeamMembersVo;
import com.api.league.vo.LeagueTeamVo;
import com.api.user.service.TeamService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.util.Sqls;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author RenQiang
 * @date 2021/5/28
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class LeagueTeamServiceImpl extends AbstractService<LeagueTeam> implements LeagueTeamService {
    private final LeagueTeamMapper leagueTeamMapper;
    private final TeamService teamService;

    public LeagueTeamServiceImpl(LeagueTeamMapper leagueTeamMapper, TeamService teamService) {
        this.leagueTeamMapper = leagueTeamMapper;
        this.teamService = teamService;
    }

    @Override
    public void deleteByTeamIds(Long leagueId, Collection<Long> teamIds) {
        apiMapper.deleteByCondition(Condition.builder(LeagueTeam.class)
                .where(Sqls.custom().andEqualTo("leagueId", leagueId)
                        .andIn("teamId", teamIds))
                .build());
    }

    @Override
    public PageInfo<LeagueTeamVo> findByPage(Map<String, Object> conditionMap, Integer page, Integer size) {
        PageHelper.startPage(page, size);
        List<LeagueTeamVo> pageData = leagueTeamMapper.findByPage(conditionMap);
        PageInfo<LeagueTeamVo> pageInfo = new PageInfo<>(pageData);
        if (CollectionUtils.isEmpty(pageInfo.getList())) {
            return pageInfo;
        }
        List<Long> teamIds = pageData.stream()
                .map(LeagueTeamVo::getTeamId)
                .distinct()
                .collect(Collectors.toList());
        Map<Long, List<Integer>> teamIdRanksMap = teamService.batchCountRank(teamIds);
        for (LeagueTeamVo leagueTeamVo : pageData) {
            leagueTeamVo.setChampions(teamIdRanksMap.get(leagueTeamVo.getTeamId()).get(0));
            leagueTeamVo.setRunnerUps(teamIdRanksMap.get(leagueTeamVo.getTeamId()).get(1));
            leagueTeamVo.setThirdPlaces(teamIdRanksMap.get(leagueTeamVo.getTeamId()).get(2));
        }
        return pageInfo;
    }

    @Override
    public List<LeagueTeamMembersVo> listDetail(Long leagueId, Map<String, Object> conditions) {
        return leagueTeamMapper.listDetail(leagueId, conditions);
    }
}
